package com.ruoyi.rsikManage.controller;


import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;

import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.rsikManage.controller.util.DateTimeUtil;
import com.ruoyi.rsikManage.controller.util.PageUtils;
import com.ruoyi.rsikManage.domain.AlarmEvent;
import com.ruoyi.rsikManage.domain.AlarmEventDto;
import com.ruoyi.rsikManage.domain.common.StatisticsRequest;
import com.ruoyi.rsikManage.domain.vo.AlarmUrlVo;
import com.ruoyi.rsikManage.domain.vo.AlarmtoSiteVo;
import com.ruoyi.rsikManage.domain.vo.ChartVo;
import com.ruoyi.rsikManage.service.AlarmEventService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;


/**
 * @author
 * @description
 * @date 2023/8/9 16:56
 */
@RequestMapping("")
@RestController
@Slf4j
@SuppressWarnings("all")
public class AlarmEventController extends BaseController {
    @Autowired
    private AlarmEventService alarmEventService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ServletContext servletContext;

    @Autowired
    private TokenService tokenService;

    private HttpHeaders headers = new HttpHeaders();
    private List<String> xList = new ArrayList<>();
    private List<String> yList = new ArrayList<>();
    private List<String> typeList = new ArrayList<>();
    private List<Map<String, Object>> pointsList = new ArrayList<>();
    private HashMap<String, Object> param = new HashMap<>();
    private List<String> apeList = new ArrayList<>();
    private List<String> idsList = new ArrayList<>();


    String x = null;
    String y = null;
    String user = "usercode:YGSJ";
    String cookie = "usercode=YGSJ";
    String contentType = "application/json";
    private final String DICT_TYPE = "alarm_level";
    private Date date = new Date();
    private final static String approveDict = "approve";
    private final static String alarmLevelDict = "alarm_level";

    /**
     * 设置请求头参数
     */
   /* public void setHeaders(HttpHeaders headers) {
        headers.set("Authorization", servletContext.getAttribute("access_token").toString());
        headers.set("Content-Type", contentType);
    }*/
    // 分页查询(未过滤)
    @PostMapping("/alarmEvent/insert")
    public AjaxResult insertAlarmEvent(@RequestBody AlarmEvent alarmEvent) {

        int i = alarmEventService.insertAlarm(alarmEvent);
        if(i>0) {
            return AjaxResult.success("入库成功");
        }else {
            return AjaxResult.error("入库失败");
        }
    }



    @PostMapping("/alarmEvent/insertBatch")
    public AjaxResult insertAlarmEvents(@RequestBody List<AlarmEvent> alarmEvents) {
        if (CollectionUtils.isEmpty(alarmEvents)) {
            return AjaxResult.error("传入的事件列表为空");
        }
        int insertedCount = alarmEventService.insertAlarmBatch(alarmEvents);
        if (insertedCount > 0) {
            return AjaxResult.success("成功入库 " + insertedCount + " 条事件");
        } else {
            return AjaxResult.error("批量入库失败");
        }
    }

    // 分页查询(未过滤)
    @GetMapping("/alarmEvent/list")
    public TableDataInfo selectPageAlarmEvent(AlarmEvent alarmEvent) {
        apeList.clear();
        idsList.clear();
        Map<String, Object> maps = getLists(alarmEvent);
        ArrayList<AlarmEvent> alarmEventArrayList = new ArrayList<>();
        List<AlarmEvent> willList = (List<AlarmEvent>) maps.get("list3");
        List<AlarmEvent> noList = (List<AlarmEvent>) maps.get("list");
        for (AlarmEvent event : willList) {
            alarmEventArrayList.add(event);
        }
        for (AlarmEvent event : noList) {
            alarmEventArrayList.add(event);
        }

        PageUtils.startPage(1, 10);
        Collections.sort(alarmEventArrayList, new Comparator<AlarmEvent>() {
            @Override
            public int compare(AlarmEvent o1, AlarmEvent o2) {
                return o2.getAlarmTime().compareTo(o1.getAlarmTime());
            }
        });

        return PageUtils.getDataTable(alarmEventArrayList);
    }

    private Map<String, Object> getLists(AlarmEvent alarmEvent) {
        List<AlarmEvent> list = null;
        Map<String, Object> map = null;

        //List<AlarmEvent> list = alarmEventService.selectPageAlarmEvent(alarmEvent);

        // 设置三年前第一天和当年最后一天
        List<AlarmEventDto> list1 = alarmEventService.selectApproal(DateTimeUtil.getCurrYearFirst(), DateTimeUtil.getCurrYearLast());
        for (AlarmEventDto alarmEventDto : list1) {
            String apeId = alarmEventDto.getApeId();
            Date startTime1 = alarmEventDto.getStartTime();
            Date endTime1 = alarmEventDto.getEndTime();
            //3.1 根据获取的id和时间查询报警信息表中的数据列表id
            List<Map> list2 = alarmEventService.selectAlarmEventByTimeandApeId(apeId, startTime1, endTime1);
            for (Map map1 : list2) {
                String idId = map1.get("id_id").toString();
                apeList.add(idId);

            }

        }
        Iterator<String> iterator = apeList.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            if (apeList.indexOf(str) != apeList.lastIndexOf(str)) {
                iterator.remove();
            }
        }
        // 根据id获取对应的数据
        List<AlarmEvent> list3 = alarmEventService.selectByIds(apeList);

        for (AlarmEvent event : list3) {
            event.setEventFlag("已报备");

        }
        // 获取表中所有的id集合
        List<AlarmEvent> idList = alarmEventService.selectPageAlarmEvent(alarmEvent);
        for (AlarmEvent event : idList) {
            String s = event.getIdId().toString();
            idsList.add(s);
        }
        // 减
        ArrayList<String> arrayList = new ArrayList<>();
        HashSet<String> hs1 = new HashSet<>(idsList);
        HashSet<String> hs2 = new HashSet<>(apeList);
        hs1.removeAll(hs2);
        arrayList.addAll(hs1);
        System.out.println(arrayList);


        if (!arrayList.isEmpty()) {
            list = alarmEventService.selectByIds(arrayList);
            for (AlarmEvent event : list) {
                event.setEventFlag("未报备");
            }
        }
        /*setHeaders(headers);
        String url = "http://192.168.14.205:11125/api/mg/v2/fms/files/url/translate";
        String[] urlArr1 = new String[list3.size()];
        for (int i = 0; i < list3.size(); i++) {
            urlArr1[i] = list3.get(i).getPictureUrl();
        }
        System.out.println(Arrays.toString(urlArr1));
        // 获取http请求对象
        HttpEntity httpEntity1 = new HttpEntity<>(urlArr1, headers);
        ResponseEntity<Map> response1 = restTemplate.postForEntity(url, httpEntity1, Map.class);
        Map<String, Object> body1 = response1.getBody();
        List<String> listStr1 = (List<String>) body1.get("data");
        System.out.println("listStr1" + listStr1);
        for (int i = 0; i < list3.size(); i++) {
            AlarmEvent event2 = list3.get(i);
            event2.setPictureUrl(listStr1.get(i));
        }*/

        map = new HashMap<String, Object>();
        map.put("list3", list3);

        if (!arrayList.isEmpty()) {
           /* String[] urlArr = new String[list.size()];
            for (int i = 0; i < urlArr.length; i++) {
                urlArr[i] = list.get(i).getPictureUrl();
            }
            System.out.println(Arrays.toString(urlArr));
            HttpEntity httpEntity = new HttpEntity<>(urlArr, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, httpEntity, Map.class);
            Map<String, Object> body = response.getBody();
            List<String> listStr = (List<String>) body.get("data");
            System.out.println("listStr" + listStr);
            for (int i = 0; i < list.size(); i++) {
                AlarmEvent event2 = list.get(i);
                event2.setPictureUrl(listStr.get(i));
            }*/

            map.put("list", list);

        }

        return map;
    }


    // 分页查询(过滤)selectCondition
    @GetMapping("/alarmEvent/condition")
    public TableDataInfo selectCondition(AlarmEvent alarmEvent) {
        apeList.clear();
        List<AlarmEvent> list = this.getAlarmEvents(alarmEvent);
        PageUtils.startPage(1, 10);
        Collections.sort(list, new Comparator<AlarmEvent>() {
            @Override
            public int compare(AlarmEvent o1, AlarmEvent o2) {
                return o2.getAlarmTime().compareTo(o1.getAlarmTime());
            }
        });
        return PageUtils.getDataTable(list);
    }


    private List<AlarmEvent> getAlarmEvents(AlarmEvent alarmEvent) {
        // 1. 获取请求参数,查询报备表中中的开始时间,结束时间
        Date startTime = alarmEvent.getStartTime();
        Date endTime = alarmEvent.getEndTime();
        Calendar calendar = null;
        Calendar calendar1 = null;
        List<AlarmEvent> list = null;
        List<AlarmEventDto> list1 = null;
        if (startTime == null || endTime == null) {
            // 获取当前日期
            // 创建calendar对象,并设置当前日期
            calendar = Calendar.getInstance();
            calendar.setTime(date);
            //将日期设置为上一个月
            calendar.add(Calendar.MONTH, -1);
            //获取上个月的日期
            calendar.set(Calendar.DAY_OF_MONTH, 1); //设置上个月的1号
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            startTime = calendar.getTime();
            System.out.println("第一天日期时间为:" + calendar.getTime());
            // 获取上月最后一天日期
            calendar1 = Calendar.getInstance(); // 获取当前日期
            calendar1.set(Calendar.DAY_OF_MONTH, 0); //设置为0号,即最后一天日期
            calendar1.set(Calendar.HOUR_OF_DAY, 23);
            calendar1.set(Calendar.MINUTE, 59);
            calendar1.set(Calendar.SECOND, 59);
            endTime = calendar1.getTime();
            System.out.println("最后一天日期时间为:" + calendar1.getTime());
        }
        //2. 根据sql查询出对应的数据列表
        list1 = alarmEventService.selectApproal(startTime, endTime);
        if (list1.size() == 0) {
            System.out.println("该时间段内未存在报备信息的数据");
        }
        //3. 遍历获取id,时间段
        for (AlarmEventDto alarmEventDto : list1) {
            String apeId = alarmEventDto.getApeId();
            Date startTime1 = alarmEventDto.getStartTime();
            Date endTime1 = alarmEventDto.getEndTime();
            //3.1 根据获取的id和时间查询报警信息表中的数据列表id
            List<Map> list2 = alarmEventService.selectAlarmEventByTimeandApeId(apeId, startTime1, endTime1);
            for (Map map : list2) {
                String idId = map.get("id_id").toString();
                apeList.add(idId);
            }
        }
        alarmEvent.setList(apeList);
     /*   setHeaders(headers);
        String url = "http://192.168.14.205:11125/api/mg/v2/fms/files/url/translate";
        startPage();*/

        //4.将查询到的数据进行过滤,然后展示过滤后的数据
        try {
            list = alarmEventService.selectCondition(alarmEvent);
            for (AlarmEvent event : list) {
                event.setEventFlag("未报备");
            }

        } catch (Exception e) {
            list = alarmEventService.selectAll(startTime, endTime);
            //list = alarmEventService.selectCondition(alarmEvent);
            // return AjaxResult.error("上月无数据");
            //throw new RuntimeException("无数据");

        }
       /* String[] urlArr = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            urlArr[i] = list.get(i).getPictureUrl();
        }
        System.out.println(Arrays.toString(urlArr));
        // 获取http请求对象
        HttpEntity httpEntity = new HttpEntity<>(urlArr, headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(url, httpEntity, Map.class);
        Map<String, Object> body = response.getBody();
        List<String> listStr = (List<String>) body.get("data");
        System.out.println("listStr" + listStr);
        for (int i = 0; i < list.size(); i++) {
            AlarmEvent event = list.get(i);
            event.setPictureUrl(listStr.get(i));
        }*/
        return list;
    }


    // 修改
    @PutMapping("/alarmEvent")
    public AjaxResult updateAlarmEvent(@RequestBody Map<String, Object> params) {
        return toAjax(alarmEventService.updateAlarmEvent(params));

    }

    //删除
    @DeleteMapping("/alarmEvent/{ids}")
    public AjaxResult deleteAlarmEvent(@PathVariable Long[] ids) {
        return toAjax(alarmEventService.deleteAlarmEvent2(ids));
    }

    //报警事件处理功能
    @PutMapping("/alarmEvent/dispose")
    public AjaxResult updateDispose(@RequestBody Map<String, Object> params) {

        return toAjax(alarmEventService.updateDispose(params));
    }

    //接收报警数据
    @RequestMapping(value = "/getdata", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult query2GroupDay(@RequestBody(required = false) Map map) throws IOException {
        xList.clear();
        yList.clear();
        typeList.clear();
        pointsList.clear();
        param.clear();
//        Map<String, Object> maps = (Map<String, Object>) map.get("data");
        Map<String, Object> maps = JSON.parseObject(map.get("data").toString());
        String eventType = map.get("event_type").toString();
        String eventId = map.get("event_id").toString();
        String alarmLevel = maps.get("alarm_level").toString();
        String alarmLevelName = maps.get("alarm_level_name").toString();
        String alarmType = maps.get("alarm_type").toString();
        String alarmTypeName = maps.get("alarm_type_name").toString();
        String device_id = maps.get("device_id").toString();
        String deviceName = maps.get("device_name").toString();
        String idStr = maps.get("id").toString();
        String orgIndex = maps.get("org_index").toString();
        String orgName = maps.get("org_name").toString();
        String pictureUrl = maps.get("picture_url").toString();
        String timeForStr = maps.get("alarm_time").toString();
        Long currentMilltimes = Long.valueOf(timeForStr);
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentMilltimes);
        //Date date = new Date(currentMilltimes);
        System.out.println("转换后的格式为:" + currentTime);
        log.debug("--------------------------------转换成功-------------------------");
// ---------------------------------------------------------------------------------------------

        Map<String, Object> bizJson = (Map<String, Object>) maps.get("biz_json");
        String algoId = bizJson.get("algo_id").toString();
        String posY = bizJson.get("pos_y").toString();
        String posX = bizJson.get("pos_x").toString();
        String puId = bizJson.get("pu_id").toString();
        String confidence = bizJson.get("confidence").toString();
        String width = bizJson.get("width").toString();
        String puName = bizJson.get("pu_name").toString();
        String height = bizJson.get("height").toString();
        String status = bizJson.get("status").toString();
        String puIdx = bizJson.get("pu_idx").toString();
        Long id = Long.valueOf(idStr);


// ------------------------------------------------------------------------------------------

        List<Map<String, Object>> osd = (List<Map<String, Object>>) bizJson.get("osd");
        osd.forEach(new Consumer<Map<String, Object>>() {
            @Override
            public void accept(Map<String, Object> map) {
                String type = map.get("type").toString();
                pointsList = (List<Map<String, Object>>) map.get("points");
                typeList.add(type);
                pointsList.forEach(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> map) {
                        x = map.get("x").toString();
                        y = map.get("y").toString();
                        xList.add(x);
                        yList.add(y);
                    }
                });
            }
        });
        /*points.forEach(new Consumer<Map<String, Object>>() {
            @Override
            public void accept(Map<String, Object> map) {
                x = map.get("x").toString();
                y = map.get("y").toString();
                xList.add(x);
                yList.add(y);
            }
        });*/
      /*  param.put("location", JSON.toJSONString(xList) + "="+JSON.toJSONString(yList));
        param.put("type", JSON.toJSONString(typeList));*/
        param.put("eventType", eventType);
        param.put("eventId", eventId);
        param.put("alarmLevel", alarmLevel);
        param.put("alarmLevelName", alarmLevelName);
        param.put("alarmType", alarmType);
        param.put("alarmTypeName", alarmTypeName);
        param.put("deviceId", device_id);
        param.put("deviceName", deviceName);
        param.put("alarmTime", currentTime);
        param.put("id", id);
        param.put("orgIndex", orgIndex);
        param.put("orgName", orgName);
        param.put("pictureUrl", pictureUrl);
//        param.put("deviceId", deviceId);
        //param.put("type", typeList);
      /*  param.put("x", xList);
        param.put("y", yList);*/
        // param.put("algoId", algoId);
        //param.put("posY", posY);
        //param.put("posX", posX);
        //param.put("puId", puId);
        //param.put("confidence", confidence);
        //param.put("width", width);
        param.put("puName", puName);
        //param.put("height", height);
        //param.put("puIdx", puIdx);
        //param.put("points", points);
        alarmEventService.insertAlarmEvent(param);

        System.out.println("----------------------------最外层-------------------------------------");
        System.out.println("event_type:" + eventType);
        System.out.println("event_id:" + eventId);
        System.out.println("alarmlevel" + ":" + alarmLevel);
        System.out.println("alarmLevelName" + ":" + alarmLevelName);
        System.out.println("alarmType" + ":" + alarmType);
        System.out.println("alarmTypeName" + ":" + alarmTypeName);
        System.out.println("device_id" + ":" + device_id);
        System.out.println("device_name" + ":" + deviceName);
        System.out.println("id" + ":" + id);
        System.out.println("orgIndex" + ":" + orgIndex);
        System.out.println("orgName" + ":" + orgName);
        System.out.println("pictureUrl" + ":" + pictureUrl);
        //System.out.println("deviceId" + ":" + deviceId);
        System.out.println("alarmTime" + currentTime);
        System.out.println("-----------------------------第二层----------------------------------");
        System.out.println("bizJson" + ":" + bizJson);
        System.out.println("algoId" + ":" + algoId);
        System.out.println("posY" + ":" + posY);
        System.out.println("posX" + ":" + posX);
        System.out.println("puId" + ":" + puId);
        System.out.println("confidence" + ":" + confidence);
        System.out.println("width" + ":" + width);
        System.out.println("puName" + ":" + puName);
        System.out.println("height" + ":" + height);
        System.out.println("status" + ":" + status);
        System.out.println("puIdx" + ":" + puIdx);
        System.out.println("-----------------------------最后一层----------------------------------");
        System.out.println("osd" + ":" + osd);
        // System.out.println("points" + ":" + pointsList);
        System.out.println("typeList" + typeList);
        System.out.println("xList" + xList);
        System.out.println("yList" + yList);

     /*   LocalDate now = LocalDate.now();

        System.out.println(now);
        System.out.println(map);*/

        return AjaxResult.success("入库成功");
    }

    /**
     * 报警统计分析页-报警次数统计
     * 修改时间 2024-10-21
     */
    // 报警次数统计
    @GetMapping("/alarmEvent/count/v2")
    public AjaxResult selectAlarmNumCount(@RequestParam String startTime, @RequestParam String endTime) {
        startTime = startTime+" 00:00:00";
        endTime = endTime+" 23:59:59";
        // 获取当前登录用户的单位代码
        //  1.查询总数
        List<Map> list = alarmEventService.selectAlarmNumCount(startTime, endTime);
        HashMap<String, Object> allMap = new HashMap<>();
        ArrayList<Integer> list1 = new ArrayList<>();
        for (Map map : list) {
            String numStr = map.get("num").toString();
            int num = Integer.parseInt(numStr);
            list1.add(num);
        }
        List<Integer> collect = list1.stream().collect(Collectors.toList());
        allMap.put("numList", collect);
        // 2.查询查询每个类型的报警数量
        //2.1 查询出类型长度
        int size = alarmEventService.selectDictSize(DICT_TYPE);
        // 2.2 遍历获取每个类型的数量和类型名称
        ArrayList<String> numList = new ArrayList<>();
        ArrayList<String> alarmLevelList = new ArrayList<>();
        HashMap<String, Object> everyMap = new HashMap<>();
        // List<String> alarmTypelist = alarmEventService.selectAlarmTypeName();

        for (int i = 3; i <= size+2; i++) {
            Map<String, Object> map = alarmEventService.selectEveryTypeNum(startTime, endTime, i);
            String num = map.get("num").toString();
            String alarmLevel = map.get("alarm_level") == null ? String.valueOf(i) : map.get("alarm_level").toString();
            numList.add(num);
        }


        alarmLevelList.add("Ⅲ级报警");
        alarmLevelList.add("Ⅱ级报警");
        alarmLevelList.add("Ⅰ级报警");

        int alarmCountLevelSum=0;
        for (String num: numList){
            int i = Integer.parseInt(num);
            alarmCountLevelSum=i+alarmCountLevelSum;
        }

        everyMap.put("numList", numList);
        everyMap.put("alarmCountSum", alarmCountLevelSum);
        everyMap.put("nameList", alarmLevelList);


        /*------------------------------------------------------------------------------------------------*/

        ArrayList<String> dicKeyList = new ArrayList<>();
        ArrayList<String> dicValueList = new ArrayList<>();

        ArrayList<List<String>> idsList = new ArrayList<>();

        ArrayList<List<String>> monitorIdsList = new ArrayList<>();
        ArrayList<String> alarmtoSiteVoNumList = new ArrayList<>();

        List<AlarmtoSiteVo> voList = alarmEventService.selectStandsPlace();
        for (AlarmtoSiteVo alarmtoSiteVo : voList) {
            dicKeyList.add(alarmtoSiteVo.getDicKey());
            dicValueList.add(alarmtoSiteVo.getDicValue());
        }
        for (int i = 0; i < dicValueList.size(); i++) {
            ArrayList<String> idList = new ArrayList<>();
            List<AlarmtoSiteVo> voList2 = alarmEventService.selectByDicValue(dicValueList.get(i));
            for (AlarmtoSiteVo alarmtoSiteVo : voList2) {
                idList.add(alarmtoSiteVo.getId());

            }
            idsList.add(idList);
        }
        for (List<String> stringList : idsList) {
            ArrayList<String> monitorIdList = new ArrayList<>();
            List<AlarmtoSiteVo> voList3 = alarmEventService.selectBymonitorIds(stringList);
            for (AlarmtoSiteVo alarmtoSiteVo : voList3) {
                monitorIdList.add(alarmtoSiteVo.getMonitorId());
            }
            monitorIdsList.add(monitorIdList);

        }
        for (List<String> stringList : monitorIdsList) {
            if (stringList.size() != 0) {
                List<AlarmtoSiteVo> voList4 = alarmEventService.selectByDeviceIds(startTime, endTime, stringList);
                voList4.forEach(new Consumer<AlarmtoSiteVo>() {
                    @Override
                    public void accept(AlarmtoSiteVo alarmtoSiteVo) {
                        alarmtoSiteVoNumList.add(alarmtoSiteVo.getAlarmCount());
                    }
                });
            } else {
                alarmtoSiteVoNumList.add("0");
            }
        }
        int alarmCountSum=0;
       for (String num: alarmtoSiteVoNumList){
           int i = Integer.parseInt(num);
           alarmCountSum=i+alarmCountSum;
       }


        HashMap<String, Object> threePointMap = new HashMap<>();
        threePointMap.put("dicKeyList", dicKeyList);
        threePointMap.put("alarmCountSum", alarmCountSum);
        threePointMap.put("alarmtoSiteVoNumList", alarmtoSiteVoNumList);
        //threePointMap.put("monitorIdList", monitorIdList);
        // threePointMap.put("idList", idList);
        //  threePointMap.put("dicValueList", dicValueList);

        HashMap<String, Object> countMap = new HashMap<>();
        countMap.put("allMap", allMap);
        countMap.put("everyMap", everyMap);
        countMap.put("threePointMap", threePointMap);
        return AjaxResult.success(countMap);
    }

    /**
     * 报警统计分析页 - 报警次数统计
     *
     * 该方法用于统计在指定时间范围内的报警次数。
     * 创建时间: 2024-10-21
     *
     * @param startTime 开始时间，用于限定统计的时间范围的起始点。
     * @param endTime 结束时间，用于限定统计的时间范围的结束点。
     * @param unitCodes 筛选的煤矿编码数组。
     * @return 返回一个包含报警次数的映射，其中键为 "num"，值为报警次数。
     */
    // 报警次数统计
    @PostMapping ("/alarmEvent/count")
    public AjaxResult selectAlarmNumCountV2(
            @RequestBody(required = false) StatisticsRequest statisticsRequest,
            HttpServletRequest httpServletRequest) {

        LocalDateTime startTime = statisticsRequest.getStartTime();
        LocalDateTime endTime = statisticsRequest.getEndTime();
        LocalDateTime now = LocalDateTime.now();

        // 如果 startTime 未被设置，则默认为当天的开始时间 (00:00:00)
        if (startTime == null) {
            startTime = now.toLocalDate().atStartOfDay();
        }

        // 如果 endTime 未被设置，则默认为当天的结束时间 (23:59:59.999999999)
        if (endTime == null) {
            endTime = now.toLocalDate().atTime(23, 59, 59, 999_999_999);
        }
        // 初始化单位代码列表
        List<Long> unitCodes = new ArrayList<>();

        // 如果请求体不为空，则从请求体中获取单位代码
        if (statisticsRequest != null) {
            unitCodes = statisticsRequest.getUnitCodes();
        }
        // 如果单位代码列表为空，则尝试从当前登录用户获取单位代码
        if (unitCodes == null || unitCodes.isEmpty()) {
            if (httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null) {
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            }
        }

        // 1. 查询总报警数量
        // 调用服务层方法获取总报警数量
        List<Map> totalAlarms = alarmEventService.selectAlarmNumCountV2(startTime, endTime,unitCodes);
        // 使用流操作将每个报警数量从字符串转换为整数，并收集到列表中
        List<Integer> totalAlarmCounts = totalAlarms.stream()
                .map(map -> Integer.parseInt(map.get("num").toString()))
                .collect(Collectors.toList());
        // 2. 查询每种级别的报警数量
        // 获取报警级别的数量
        int size = alarmEventService.selectDictSize(DICT_TYPE);
        // 初始化存储每种级别报警数量和名称的列表
        ArrayList<String> numList = new ArrayList<>();
        ArrayList<String> alarmLevelList = new ArrayList<>(Arrays.asList("Ⅲ级报警", "Ⅱ级报警", "Ⅰ级报警"));
        HashMap<String, Object> everyMap = new HashMap<>();

        // 遍历每个报警级别，获取每个级别的报警数量
        for (int i = 3; i <= size + 2; i++) {
            Map<String, Object> map = alarmEventService.selectEveryTypeNumForUnitCodes(startTime, endTime, i,unitCodes);
            if (map!=null){
                numList.add(map.get("num").toString());
            }else {
                numList.add("0");
            }

        }

        // 计算所有级别报警数量的总和
        int alarmCountLevelSum = numList.stream()
                .map(Integer::parseInt)
                .reduce(0, Integer::sum);

        // 将每种级别的报警数量和总和存入Map中
        everyMap.put("numList", numList);
        everyMap.put("alarmCountSum", alarmCountLevelSum);
        everyMap.put("nameList", alarmLevelList);

        // 3. 查询特定地点的报警数量
        // 初始化存储地点信息的列表
        ArrayList<String> dicKeyList = new ArrayList<>();
        ArrayList<String> dicValueList = new ArrayList<>();
        ArrayList<List<String>> idsList = new ArrayList<>();
        ArrayList<List<String>> monitorIdsList = new ArrayList<>();
        ArrayList<String> alarmtoSiteVoNumList = new ArrayList<>();

        // 获取所有地点的信息
        List<AlarmtoSiteVo> voList = alarmEventService.selectStandsPlace();
        for (AlarmtoSiteVo alarmtoSiteVo : voList) {
            dicKeyList.add(alarmtoSiteVo.getDicKey());
            dicValueList.add(alarmtoSiteVo.getDicValue());
        }

        // 根据dicValue获取每个地点的id列表
        for (String dicValue : dicValueList) {
            List<AlarmtoSiteVo> voList2 = alarmEventService.selectByDicValue(dicValue);
            List<String> idList = voList2.stream()
                    .map(AlarmtoSiteVo::getId)
                    .collect(Collectors.toList());
            idsList.add(idList);
        }

        // 根据id列表获取每个地点的监控设备id列表
        for (List<String> idList : idsList) {
            List<AlarmtoSiteVo> voList3 = alarmEventService.selectBymonitorIds(idList);
            List<String> monitorIdList = voList3.stream()
                    .map(AlarmtoSiteVo::getMonitorId)
                    .collect(Collectors.toList());
            monitorIdsList.add(monitorIdList);
        }

        // 根据监控设备id列表获取每个地点的报警数量
        for (List<String> monitorIdList : monitorIdsList) {
            if (!monitorIdList.isEmpty()) {
                List<AlarmtoSiteVo> voList4 = alarmEventService.selectByDeviceIdsForUnitCodes(startTime, endTime, monitorIdList,unitCodes);
                List<String> alarmCounts = voList4.stream()
                        .map(AlarmtoSiteVo::getAlarmCount)
                        .collect(Collectors.toList());
                alarmtoSiteVoNumList.addAll(alarmCounts);
            } else {
                alarmtoSiteVoNumList.add("0");
            }
        }

        // 计算所有地点报警数量的总和
        int alarmCountSum = alarmtoSiteVoNumList.stream()
                .map(Integer::parseInt)
                .reduce(0, Integer::sum);

        // 构建特定地点的报警数量Map
        HashMap<String, Object> threePointMap = new HashMap<>();
        threePointMap.put("dicKeyList", dicKeyList);
        threePointMap.put("alarmCountSum", alarmCountSum);
        threePointMap.put("alarmtoSiteVoNumList", alarmtoSiteVoNumList);

        // 构建最终的响应Map
        HashMap<String, Object> countMap = new HashMap<>();
        HashMap<String, Object> allMap = new HashMap<>();
        allMap.put("numList", totalAlarmCounts);
        countMap.put("allMap", allMap);
        countMap.put("everyMap", everyMap);
        countMap.put("threePointMap", threePointMap);

        // 返回成功响应
        return AjaxResult.success(countMap);
    }
    //
    @GetMapping("/alarmEvent/dayAnalysis")
    public AjaxResult selectAnaysisc() {
        // 获取开始时间戳
        long startTime = System.currentTimeMillis();
        // 监控点统计
        Map<String, Object> map = alarmEventService.selectPointNum();
        String num = map.get("num").toString();
        ArrayList<String> pointList = new ArrayList<>();
        pointList.add(num);
        HashMap<String, Object> pointMap = new HashMap<>();
        pointMap.put("pointList", pointList);
        //报警总数统计
        Map<String, Object> dayMap = alarmEventService.selectCountDay();
        String dayNum = dayMap.get("num").toString();
        ArrayList<String> dayNumList = new ArrayList<>();
        dayNumList.add(dayNum);
        HashMap<String, Object> dayNumMap = new HashMap<>();
        pointMap.put("dayNumList", dayNumList);

        // 获取结束时间戳
        long endTime3 = System.currentTimeMillis();

        // 打印查询时间
        long queryTime3 = endTime3 - startTime;
        System.out.println("查询时间：" + queryTime3 + "毫秒");

        ArrayList<String> pathList = new ArrayList<>();
        ArrayList<String> namesList = new ArrayList<>();

        List<AlarmUrlVo> list1 = alarmEventService.selectName();
        ArrayList<AlarmUrlVo> alarmUrlVos1 = new ArrayList<>();
        AlarmUrlVo alarmUrlVos = new AlarmUrlVo();
        for (AlarmUrlVo alarmUrlVo : list1) {
            String name = alarmUrlVo.getName();
            String url = alarmUrlVo.getUrl();
            alarmUrlVos.setName(name);
            alarmUrlVos.setUrl(url);
            alarmUrlVos1.add(alarmUrlVos);
            alarmUrlVos = new AlarmUrlVo();
        }


        //getTransFromURL(list1);
// 分类型统计
        List<Map> numTypeList = alarmEventService.selectByType();
//  查询具体3种类型对应的数量
        // 查询有几种等级
        List<String> list2 = alarmEventService.selectLevel();
        //查询有几种类型
        List<String> list3 = alarmEventService.selectType();
        // 根据类型和等级查询对应的报警次数
        Map<String, Object> level1 = new HashMap<>();
        Map<String, Object> level2 = new HashMap<>();
        Map<String, Object> level3 = new HashMap<>();
//  创建专门存储某一个等级报警的所有URL
        ArrayList<List<AlarmUrlVo>> threeUrlList1 = new ArrayList<>();
        ArrayList<List<AlarmUrlVo>> threeUrlList2 = new ArrayList<>();
        ArrayList<List<AlarmUrlVo>> threeUrlList3 = new ArrayList<>();
        // 获取结束时间戳
        long endTime4 = System.currentTimeMillis();

        // 打印查询时间
        long queryTime4 = endTime4 - startTime;
        System.out.println("查询时间：" + queryTime4 + "毫秒");

        if (list3 != null && list3.size() > 0) {
            for (String s1 : list2) {
                List<AlarmUrlVo> types = alarmEventService.selectFiveTypes(s1, list3.get(0));
                List<AlarmUrlVo> urls = alarmEventService.selectUrls(s1, list3.get(0));
                //  getTransFromURL(types);
                if (types.size() != 0) {
                    for (int i = 0; i < types.size(); i++) {
                        String label = DictUtils.getDictLabel(alarmLevelDict, types.get(i).getLevel(), DictUtils.SEPARATOR);
                        types.get(i).setLevel(label);
                        if (types.get(i).getLevel().equals("一级报警")) {
                            level1.put("一级报警", types.get(i).getNum());
                            level1.put("type", list3.get(0));
                            //threeUrlList1.add(types.get(i).getUrl());
                            threeUrlList1.add(urls);
                        } else if (types.get(i).getLevel().equals("二级报警")) {
                            level2.put("二级报警", types.get(i).getNum());
                            level2.put("type", list3.get(0));
                            //threeUrlList2.add(types.get(i).getUrl());
                            threeUrlList2.add(urls);
                        } else if (types.get(i).getLevel().equals("三级报警")) {
                            level3.put("三级报警", types.get(i).getNum());
                            level3.put("type", list3.get(0));
                            //threeUrlList3.add(types.get(i).getUrl());
                            threeUrlList3.add(urls);
                        }
                    }

                }


            }
        }


        Map<String, Object> level4 = new HashMap<>();
        Map<String, Object> level5 = new HashMap<>();
        Map<String, Object> level6 = new HashMap<>();
        ArrayList<List<AlarmUrlVo>> threeUrlList4 = new ArrayList<>();
        ArrayList<List<AlarmUrlVo>> threeUrlList5 = new ArrayList<>();
        ArrayList<List<AlarmUrlVo>> threeUrlList6 = new ArrayList<>();


        if (list3 != null && list3.size() > 1) {
            for (String s1 : list2) {
                List<AlarmUrlVo> types = alarmEventService.selectFiveTypes(s1, list3.get(1));
                List<AlarmUrlVo> urls = alarmEventService.selectUrls(s1, list3.get(1));
                //  getTransFromURL(types);
                if (types.size() != 0) {
                    types.forEach(new Consumer<AlarmUrlVo>() {
                        @Override
                        public void accept(AlarmUrlVo alarmUrlVo) {
                            String label = DictUtils.getDictLabel(alarmLevelDict, alarmUrlVo.getLevel(), DictUtils.SEPARATOR);
                            alarmUrlVo.setLevel(label);
                            if (alarmUrlVo.getLevel().equals("一级报警")) {
                                level4.put("一级报警", alarmUrlVo.getNum());
                                level4.put("type", list3.get(1));
                                //threeUrlList4.add(alarmUrlVo.getUrl());
                                threeUrlList4.add(urls);
                            } else if (alarmUrlVo.getLevel().equals("二级报警")) {
                                level5.put("二级报警", alarmUrlVo.getNum());
                                level5.put("type", list3.get(1));
                                //threeUrlList5.add(alarmUrlVo.getUrl());
                                threeUrlList5.add(urls);
                            } else if (alarmUrlVo.getLevel().equals("三级报警")) {
                                level6.put("三级报警", alarmUrlVo.getNum());
                                level6.put("type", list3.get(1));
                                //threeUrlList6.add(alarmUrlVo.getUrl());
                                threeUrlList6.add(urls);
                            }
                        }
                    });

                }


            }
        }

        // 获取结束时间戳
        long endTime5 = System.currentTimeMillis();

        // 打印查询时间
        long queryTime5 = endTime5 - startTime;
        System.out.println("查询时间：" + queryTime5 + "毫秒");
        List<String> collect1 = null;
        for (List<AlarmUrlVo> list : threeUrlList1) {
            if (list != null && list.size() != 0) {
                collect1 = list.stream().map(alarmUrlVo -> alarmUrlVo.getUrl()).collect(Collectors.toList());
            }
        }
        List<String> collect2 = null;
        for (List<AlarmUrlVo> list : threeUrlList2) {
            if (list != null && list.size() != 0) {
                collect2 = list.stream().map(alarmUrlVo -> alarmUrlVo.getUrl()).collect(Collectors.toList());
            }
        }

        List<String> collect3 = null;
        for (List<AlarmUrlVo> list : threeUrlList3) {
            if (list != null && list.size() != 0) {
                collect3 = list.stream().map(alarmUrlVo -> alarmUrlVo.getUrl()).collect(Collectors.toList());
            }
        }

        List<String> collect4 = null;
        for (List<AlarmUrlVo> list : threeUrlList4) {
            if (list != null && list.size() != 0) {
                collect4 = list.stream().map(alarmUrlVo -> alarmUrlVo.getUrl()).collect(Collectors.toList());
            }
        }
        List<String> collect5 = null;
        for (List<AlarmUrlVo> list : threeUrlList5) {
            if (list != null && list.size() != 0) {
                collect5 = list.stream().map(alarmUrlVo -> alarmUrlVo.getUrl()).collect(Collectors.toList());
            }
        }
        List<String> collect6 = null;
        for (List<AlarmUrlVo> list : threeUrlList6) {
            if (list != null && list.size() != 0) {
                collect6 = list.stream().map(alarmUrlVo -> alarmUrlVo.getUrl()).collect(Collectors.toList());
            }
        }

        level1.put("url", collect1);
        level2.put("url", collect2);
        level3.put("url", collect3);
        level4.put("url", collect4);
        level5.put("url", collect5);
        level6.put("url", collect6);
        HashMap<String, Object> fiveMap = new HashMap<>();
        fiveMap.put("level1", level1);
        fiveMap.put("level2", level2);
        fiveMap.put("level3", level3);
        fiveMap.put("level4", level4);
        fiveMap.put("level5", level5);
        fiveMap.put("level6", level6);
        HashMap<String, Object> numTypeMap = new HashMap<>();
        numTypeMap.put("numTypeList", numTypeList);
        HashMap<String, Object> urlStrMap = new HashMap<>();
        urlStrMap.put("nameList", list1);
        HashMap<String, Object> allMap = new HashMap<>();
        allMap.put("pointMap", pointMap);
        allMap.put("numTypeMap", numTypeMap);
        allMap.put("fiveMap", fiveMap);
        //allMap.put("urlStrMap", urlStrMap);
        // 获取结束时间戳
        long endTime2 = System.currentTimeMillis();

        // 打印查询时间
        long queryTime2 = endTime2 - startTime;
        System.out.println("查询时间：" + queryTime2 + "毫秒");
        return AjaxResult.success(allMap);
    }


//
    // 报警处理情况统计(图表展示)
    @GetMapping("/alarmEvent/selectApprove")
    public AjaxResult selectApproveCount(@RequestParam(value = "startTime") String startTime, @RequestParam(value = "endTime") String endTime) {
        int size = alarmEventService.selectByApproveSize();
        ArrayList<String> numList = new ArrayList<>();
        ArrayList<String> approveList = new ArrayList<>();
        for (int i = 1; i <= size; i++) {
            String strFori = String.valueOf(i);
            Map<String, Object> map = alarmEventService.selectApproveCount(startTime, endTime, strFori);
            String num = map.get("num").toString();
            numList.add(num);
            approveList.add(strFori);
        }
        ArrayList<String> nameList = new ArrayList<>();
        for (int i = 0; i < approveList.size(); i++) {
            String approve = approveList.get(i).toString();
            Map<String, Object> map = alarmEventService.selectByApproveValue(approve);
            String name = map.get("name").toString();
            nameList.add(name);
        }
        // 分类别总数统计
        HashMap<String, Object> allCountMap = new HashMap<>();
        allCountMap.put("numList", numList);
        allCountMap.put("nameList", nameList);


        // 折线图统计
        ArrayList<String> dateForList = new ArrayList<>();
        ArrayList<String> approvesList = new ArrayList<>();
        ArrayList<String> list1 = new ArrayList<>();

        ArrayList<List<ChartVo>> chartVos = new ArrayList<>();
        for (int i = 1; i <= nameList.size(); i++) {
            List<ChartVo> list = alarmEventService.selectDateCount(startTime, endTime, String.valueOf(i));
            list.forEach(new Consumer<ChartVo>() {
                @Override
                public void accept(ChartVo chartVo) {
                    String approve = chartVo.getApprove();
                    String label = DictUtils.getDictLabel(approveDict, approve, DictUtils.SEPARATOR);
                    chartVo.setApprove(label);
                }
            });
            /*for (Map map : list) {
                String dateFor = map.get("dateFor").toString();
                String approve = map.get("approve").toString();
                String label = DictUtils.getDictLabel(approveDict, approve, DictUtils.SEPARATOR);
                String num = map.get("num").toString();
                dateForList.add(dateFor);
                approvesList.add(label);
                list1.add(num);
            }*/
            chartVos.add(list);
        }




       /* for (int i = 0; i < approvesList.size(); i++) {
            list1.add(approvesList.get(i));
        }*/
        HashMap<String, Object> lineChartMap = new HashMap<>();

        /*lineChartMap.put("dateForList", dateForList);
        lineChartMap.put("approveList", approvesList);
        lineChartMap.put("numList", list1);*/
        lineChartMap.put("chartList", chartVos);
        HashMap<String, Object> allHashMap = new HashMap<>();
        allHashMap.put("allCountMap", allCountMap);
        allHashMap.put("lineChartMap", lineChartMap);
        return AjaxResult.success(allHashMap);
    }

//

}
